import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Table, Alert, Divider, Icon, message as msg} from 'antd';
import TextInput from 'Shared/components/TextInput';
import styles from './style.css';
import {PAGE, TABLE, PAGINATION_OPTIONS, COMMON_TABLE_QUERY_FAIL_TEXT, COMMON_TABLE_EMPTY_TEXT, ROWSELECTION_FIXED_COLUMN_WIDTH} from '../constants';
import WrappedTag from '../common/WrappedTag';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import {formatAmount, conventSorter} from '../utils';
import difference from 'lodash/difference';
import {getParts} from './api';
const FormItem = Form.Item;
const formItemLayout = {
    labelCol: {
        span: 8
    },
    wrapperCol: {
        span: 16
    }
};
class PartSelectPanel extends React.PureComponent {
    state = {
        code: '',
        name: '',
        pageIndex: PAGE.index,
        pageSize: PAGE.smallSize,
        sortField: 'code',
        isDesc: false,
        //点击查询后的条件,用于分页查询
        data: {},
        keys: [],
        rows: [],
        currentCondition: {},
        showTags: false
    };
    handleFilterChange = (value, name) => {
        this.setState({
            [name]: value
        });
    };

    handleFilterPressEnter = (value, name) => {
        this.setState({
            [name]: value
        }, this.onClickSearchBtn);
    };

    toggleShowTags = () => {
        this.setState({
            showTags: !this.state.showTags
        });
    };

    onClickSearchBtn = () => {
        const condition = {
            code: this.state.code,
            name: this.state.name,
            pageIndex: PAGE.index,
            pageSize: this.state.pageSize,
            sortField: this.state.sortField,
            isDesc: this.state.isDesc
        };
        this.onQuery(condition);
    };
    onQuery = condition => {
        this.setState({
            isFetching: true
        });
        getParts({
            ...condition,
            saleOrderTypeId: this.props.saleOrderTypeId
        }).then(res => {
            if(res.ok)
                this.setState({
                    isFetching: false,
                    message: '',
                    data: res.data,
                    currentCondition: condition
                });
            else
                this.setState({
                    list: {
                        isFetching: false,
                        total: 0,
                        data: {}
                    }
                });
        });
    };
    
    onChangeSort = (pagination, filters, sorter) => {
        const oldCondition = this.state.currentCondition;

        if(pagination.current - 1 === oldCondition.pageIndex && pagination.pageSize === oldCondition.pageSize) {
            const sortOptions = conventSorter(sorter);
            const condition = Object.assign({}, oldCondition, sortOptions, {
                pageIndex: PAGE.index
            });
            this.onQuery(condition);
            this.setState({
                sortField: sortOptions.sortField,
                isDesc: sortOptions.isDesc
            });
        }
    };
    onSelectChange = (keys, rows) => {
        const data = this.state.rows;
        const preSelectedKeys = this.state.keys; // 勾选行

        if(keys.length > preSelectedKeys.length)
            rows.forEach(v => {
                if(data.findIndex(d => d.id === v.id) === -1) data.push(v);
            });
        else {
            // 取消勾选
            const diffKeys = difference(preSelectedKeys, keys);
            diffKeys.forEach(k => {
                const index = data.findIndex(d => d.id === k);
                data.splice(index, 1);
            });
        }
        this.setState({
            keys,
            rows: data
        });
    };
    onConfirm = () => {
        if(!this.state.rows.length)
            return msg.warning(this.props.intl.formatMessage({
                id: 'partSelectPanel.onConfirm.message',
                defaultMessage: '勾选的备件信息不能为空'
            }));
        this.setState({isFetching: true});
        this.props.onSelect(this.state.rows).then(success => {
            if(!success)
                this.setState({isFetching: false});
        });
    };
    onClearAll = () => {
        this.setState({
            keys: [],
            rows: []
        });
    };
    onPageIndexChange = current => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = current - 1;
        this.onQuery(condition);
    };
    onPageSizeChange = (current, pageSize) => {
        const condition = {...this.state.currentCondition};
        condition.pageIndex = PAGE.index;
        condition.pageSize = pageSize;
        this.onQuery(condition);
        this.setState({
            pageSize
        });
    };
    onDelete = id => {
        const keys = this.state.keys.filter(k => k !== id);
        const rows = this.state.rows.filter(r => r.id !== id);
        this.setState({
            keys: [...keys],
            rows: [...rows]
        });
    };

    render() {
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'partSelectPanel.code',
                    defaultMessage: '备件编号'
                }),
                dataIndex: 'code',
                sorter: true,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'partSelectPanel.name',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'name',
                sorter: true,
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'partSelectPanel.unit',
                    defaultMessage: '计量单位'
                }),
                dataIndex: 'unit'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'partSelectPanel.minPackSize',
                    defaultMessage: '最小包装数'
                }),
                dataIndex: 'minPackSize'
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'partSelectPanel.isOrderable',
                    defaultMessage: '是否可采购'
                }),
                dataIndex: 'isOrderable',
                render: text => (text ? <Icon type="check" theme="outlined" /> : '')
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'partSelectPanel.wholeSalePrice',
                    defaultMessage: '批发价'
                }),
                dataIndex: 'wholeSalePrice',
                sorter: true,
                className: styles.textAlign,
                render: text => formatAmount(text)
            },
            {
                title: this.props.intl.formatMessage({
                    id: 'partSelectPanel.retailGuidePrice',
                    defaultMessage: '零售指导价'
                }),
                dataIndex: 'retailGuidePrice',
                sorter: true,
                className: styles.textAlign,
                render: text => formatAmount(text)
            }
        ];
        const {code, name, isFetching, data, message} = this.state;
        const {pageIndex, pageSize} = this.state.currentCondition;
        const pagination = {
            total: data.totalElements,
            current: pageIndex + 1,
            pageSize,
            onShowSizeChange: this.onPageSizeChange,
            onChange: this.onPageIndexChange,
            ...PAGINATION_OPTIONS
        };
        const rowSelection = {
            fixed: true,
            type: 'checkbox',
            selectedRowKeys: this.state.keys,
            onChange: this.onSelectChange,
            columnWidth: ROWSELECTION_FIXED_COLUMN_WIDTH
        };
        const alertMessage = (
            <div>
                <span>
                    {this.props.intl.formatMessage({
                        id: 'partSelectPanel.alertMessage.span',
                        defaultMessage: '已选择'
                    })}
                    <a onClick={this.toggleShowTags}>
                        {this.state.rows.length}
                        {this.props.intl.formatMessage({
                            id: 'partSelectPanel.alertMessage.a.number',
                            defaultMessage: '项'
                        })}
                    </a>
                    {this.props.intl.formatMessage({
                        id: 'partSelectPanel.alertMessage.comma',
                        defaultMessage: '，'
                    })}
                    <a onClick={this.onClearAll} className={styles.clearAllTag}>
                        {this.props.intl.formatMessage({
                            id: 'partSelectPanel.alertMessage.deleteAll',
                            defaultMessage: '清除选择'
                        })}
                    </a>
                    {this.state.rows.length ? <WrappedPopconfirm
                        id="confirm"
                        title={this.props.intl.formatMessage({
                            id: 'partSelectPanel.popconfirm.message',
                            defaultMessage: '新增后将更新清单，是否继续?'
                        })}
                        okText={this.props.intl.formatMessage({
                            id: 'partSelectPanel.popconfirm.confirm',
                            defaultMessage: '确认'
                        })}
                        cancelText={this.props.intl.formatMessage({
                            id: 'partSelectPanel.popconfirm.cancel',
                            defaultMessage: '取消'
                        })}
                        onConfirm={this.onConfirm}>
                        <Button
                            size="small"
                            type="primary"
                            className={styles.partBtn}>
                            {this.props.intl.formatMessage({
                                id: 'partSelectPanel.btn.confirm',
                                defaultMessage: '确认'
                            })}
                        </Button>
                    </WrappedPopconfirm> : <Button
                        size="small"
                        type="primary"
                        disabled
                        className={styles.partBtn}>
                        {this.props.intl.formatMessage({
                            id: 'partSelectPanel.btn.confirm',
                            defaultMessage: '确认'
                        })}
                    </Button>}
                </span>
                {this.state.showTags && (
                    <div className={styles.partTag}>
                        {this.state.rows.map(r => (
                            <WrappedTag key={r.id} closable id={r.id} onClose={this.onDelete}>
                                {r.name}
                            </WrappedTag>
                        ))}
                    </div>
                )}
            </div>
        );
        const locale = {
            emptyText: message ? COMMON_TABLE_QUERY_FAIL_TEXT : COMMON_TABLE_EMPTY_TEXT
        };
        return (
            <div>
                <Form className="form-standard">
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'partSelectPanel.code',
                                    defaultMessage: '备件编号'
                                })}
                                {...formItemLayout}>
                                <TextInput id="code" value={code} onPressEnter={this.handleFilterPressEnter} onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label={this.props.intl.formatMessage({
                                    id: 'partSelectPanel.name',
                                    defaultMessage: '备件名称'
                                })}
                                {...formItemLayout}>
                                <TextInput id="name" value={name} onPressEnter={this.handleFilterPressEnter} onBlur={this.handleFilterChange} />
                            </FormItem>
                        </Col>
                        <Col offset={1} span={3}>
                            <Button key="query" type="primary" onClick={this.onClickSearchBtn} loading={isFetching}>
                                {this.props.intl.formatMessage({
                                    id: 'partSelectPanel.btn.query',
                                    defaultMessage: '查询'
                                })}
                            </Button>
                        </Col>
                    </Row>
                </Form>
                <Divider className={styles.divider} />
                <Alert className={styles.alertMargin} type="info" message={alertMessage} showIcon />
                <Table
                    className="white-space-nowrap"
                    columns={columns}
                    dataSource={data.content}
                    rowKey="id"
                    rowSelection={rowSelection}
                    pagination={pagination}
                    onChange={this.onChangeSort}
                    loading={isFetching}
                    locale={locale}
                    {...TABLE}/>
            </div>
        );
    }
}
PartSelectPanel.propTypes = {
    saleOrderTypeId: PropTypes.string.isRequired,
    onSelect: PropTypes.func.isRequired,
    intl: PropTypes.object
};

export default injectIntl(PartSelectPanel);
